import { reactive, computed, toRefs } from 'vue';
import useDict from '@/hooks/useDict';
import { Pagination, PaginationQuery } from '@/types/table';
import { TableState, CheckAble } from '@/types/table';

const tableQuery: PaginationQuery = reactive({
    page: 0,
    size: 9,
    sort: 'id,desc',
});

// 角色信息
const state: TableState & CheckAble = reactive({
    dataSource: [],
    selectedRow: {},
    selectedRowKeys: [],
    visible: false,
    loading: false,
    pagination: {
        total: 0,
        current: computed(() => tableQuery.page + 1),
    },
});

// 获取table数据
const getTableData = async (tableQuery: PaginationQuery) => {
    state.loading = true;
    const { list, total } = await useDict(tableQuery);
    state.loading = false;
    state.dataSource = list;
    state.pagination.total = total;
};
// 设置table row key
const setRowKey = (record: { [x: string]: any }) => record.id;

// 选择项发生改变
const onSelectChange = (keys: (string | number)[]) => {
    console.log(keys);
    state.selectedRowKeys = keys;
};

// 页码改变
const handleTableChange = (pagination: Pagination) => {
    const { current } = pagination;
    tableQuery.page = current - 1;
    getTableData(tableQuery);
};

// 显示新增角色弹窗
const handleAddDict = () => {
    state.selectedRow = {};
    state.visible = true;
};

// 编辑角色
const handleEditDict = (dict: { [x: string]: any }) => {
    state.selectedRow = dict;
    state.visible = true;
};

// 取消弹窗
const handleCancle = () => {
    state.visible = false;
};

export default {
    tableQuery,
    getTableData,
    onSelectChange,
    handleTableChange,
    handleEditDict,
    handleAddDict,
    setRowKey,
    ...toRefs(state),
    handleCancle,
};
